package com.xayy.health.ds.service.impl;

import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import com.xayy.health.core.utils.DoshellUtils;
import com.xayy.health.core.utils.FileInfosUtils;
import com.xayy.health.core.utils.GetPidUtil;
import com.xayy.health.ds.model.DsHealthAlgorithmManage;
import com.xayy.health.ds.service.DsHealthAlgorithmManageService;
import com.xayy.health.mgt.model.HealthAlgorithmManage;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsHealthAlgorithmManageService实现类
 * @Auther:liuyuan
 * @Date:2025-07-07
 */
@Slf4j
@Service
public class DsHealthAlgorithmManageServiceImpl extends BaseServiceImpl<DsHealthAlgorithmManage> implements DsHealthAlgorithmManageService {
  /**
  *
  * 冗余代码，为自定义开发DS-Server接口服务
  *
  */
   private static String TABLE_NAME = "HEALTH_ALGORITHM_MANAGE";
   private String getUrl(){
      return getDsServerConfig().getUrl();
   }

    /**
     * 新增算法信息
     *
     * @param healthAlgorithmManage 算法信息
     * @param algorithmFile         算法文件
     * @return 结果日志
     */
    @Override
    public CheckResult<?> saveAlgorithmInfo(DsHealthAlgorithmManage healthAlgorithmManage, MultipartFile algorithmFile) {
        // 上传文件
        if (BeanUtil.isEmpty(algorithmFile)) {
            return CheckResult.fail("算法文件不能为空");
        }
        String filePath = null;
        try {
            if (algorithmFile.getOriginalFilename().endsWith("zip"))
                filePath = FileInfosUtils.uploadZip(algorithmFile);
            else
                filePath = FileInfosUtils.uploadFile(algorithmFile);
        } catch (Exception e) {
            return CheckResult.fail(e.getMessage());
        }
        // 校验code和和name是否重复
        List<DsHealthAlgorithmManage> selectCode =
                selectTList(DsHealthAlgorithmManage.builder().algorithmCode(healthAlgorithmManage.getAlgorithmCode()).build());
        if (CollUtil.isNotEmpty(selectCode)) {
            return CheckResult.fail("算法code:" + healthAlgorithmManage.getAlgorithmCode() + "已存在");
        }
        List<DsHealthAlgorithmManage> selectName =
                selectTList(DsHealthAlgorithmManage.builder().algorithmName(healthAlgorithmManage.getAlgorithmName()).build());
        if (CollUtil.isNotEmpty(selectName)) {
            return CheckResult.fail("算法名称:" + healthAlgorithmManage.getAlgorithmName() + "已存在");
        }
//        healthAlgorithmManage.setId(null);
        healthAlgorithmManage.setCreateTime(new Date());
        healthAlgorithmManage.setAlgorithmPath(filePath);
        healthAlgorithmManage.setTrialAddr(healthAlgorithmManage.getTrialAddr());
        healthAlgorithmManage.setPredictAddr(healthAlgorithmManage.getPredictAddr());
        healthAlgorithmManage.setServerState(false);
        String algorithmFileName = Objects.requireNonNull(algorithmFile.getOriginalFilename()).replace(".py", "");
        healthAlgorithmManage.setAlgorithmFileName(algorithmFileName);
        if (algorithmFile.getOriginalFilename().endsWith("zip"))
            healthAlgorithmManage.setStartServiceFile(healthAlgorithmManage.getStartServiceFile());
        insertT(healthAlgorithmManage);
        return CheckResult.success("算法新建成功");
    }

    /**
     * 启动算法服务
     * @param healthAlgorithmManage 算法信息
     * @return 结果日志
     */
    @Override
    public CheckResult<?> startAlgorithmServer(DsHealthAlgorithmManage healthAlgorithmManage){
        List<String> paramlist = new ArrayList<>();
        paramlist.add(healthAlgorithmManage.getAlgorithmPath() + "/" + healthAlgorithmManage.getStartServiceFile());
        DoshellUtils.onCall("python",paramlist);
        healthAlgorithmManage.setServerState(true);
        updateT(healthAlgorithmManage);
        return CheckResult.success("算法服务启动");
    }

    /**
     * 停止算法服务
     * @param healthAlgorithmManage 算法实体
     * @return 结果日志
     */
    @Override
    public CheckResult<?> stopAlgorithmServer(DsHealthAlgorithmManage healthAlgorithmManage){
        String closeResult = "";
        try {
            closeResult = GetPidUtil.stopByPid(healthAlgorithmManage.getAlgorithmPath() + "/" + healthAlgorithmManage.getStartServiceFile());
            healthAlgorithmManage.setServerState(false);
            updateT(healthAlgorithmManage);
        }catch (Exception e){
            e.printStackTrace();
        }
        log.info("算法服务停止,"+closeResult);
        return CheckResult.success("算法服务停止,"+closeResult);
    }

    /**
     * 根据类型获取可用算法列表
     *
     * @param type 1:剔野,2:填充,3:平滑,4:事后诊断,5:趋势预测
     * @return 算法列表信息
     */
    @Override
    public List<DsHealthAlgorithmManage> getAlgorithmByType(Integer type) {
        DsHealthAlgorithmManage build = DsHealthAlgorithmManage.builder().algorithmType(type).build();
        List<DsHealthAlgorithmManage> select = selectTList(build);
        return select.stream().sorted(Comparator.comparing(DsHealthAlgorithmManage::getCreateTime).reversed()).collect(Collectors.toList());
    }
}
